package gohttp

import (
	"fmt"
	"gitee.com/ymofen/gohttp/httpfs"
	v1 "gitee.com/ymofen/gohttp/v1"
	"net/http"
)

var (
	RootRouter = v1.NewBasicRouter()
)

func GetHtmlDiv(caption string, url string) string {
	return fmt.Sprintf("<div><a href=\"%s\">%s</a></div>", url, caption)
}

func HandleFunc(pattern string, fn http.HandlerFunc) bool {

	return RootRouter.Handle(pattern, fn)
}

func HttpHandle(pattern string, handler http.Handler) {
	RootRouter.Handle(pattern, handler)
}

func Handle(pattern string, handler http.Handler) bool {
	return RootRouter.Handle(pattern, handler)
}

func UnHandle(pattern string) {
	RootRouter.Delete(pattern)
}

func StartWebRoot(pattern string, rootPath string) {
	Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir(rootPath))))
}

func StartDefaultWebRoot() {
	StartWebRoot("/", "webroot/")
}

// lsttype : 0: html, 1:json
func StartHandleFileServ(pattern, path string, lsttype int, lstfiles bool) {
	fserv := httpfs.FileServer(http.Dir(path), lsttype, func(w http.ResponseWriter, r *http.Request) bool {
		return true
	})
	fserv.ListFiles = lstfiles
	Handle(pattern, http.StripPrefix(pattern, fserv))
}

func RunHttpService(addr string) error {
	def := NewGoHttpServ(addr, RootRouter)
	return def.ServeHttp("tcp4")
}

func RunHttpServiceWithHandler(addr string, handler http.Handler) error {
	def := NewGoHttpServ(addr, handler)
	return def.ServeHttp("tcp4")
}
